<template>
  <t-link
    v-permission="['system:order:set-customer-label']"
    theme="primary"
    @click="handleOpenDialog('update', { orderId: props.orderId, pageSize: -1 })"
  >
    设置客户标签
  </t-link>
  <!-- 自定义对话框 -->
  <custom-dialog
    ref="customDialogRef"
    v-slot="{ formData }"
    :api-map="{ get: getCustomerLabelPage, update: setCustomerLabel }"
    header="设置客户标签"
    :on-before-set-data="handleDialogSetData"
    :on-before-save-data="handleDialogSaveData"
    @request-success="handleDialogRequestSuccess"
  >
    <t-form-item
      v-for="(_, index) in formData.list"
      :key="_.labelType"
      :label="dictionaryStore.analysis('customer_label', _.labelType)"
      :name="`list[${index}].content`"
    >
      <t-input
        v-model:value="_.content"
        :placeholder="`请输入${dictionaryStore.analysis('customer_label', _.labelType)}`"
        clearable
      />
    </t-form-item>
  </custom-dialog>
</template>

<script setup lang="ts">
import { useTemplateRef } from 'vue';

import { getCustomerLabelPage, setCustomerLabel } from '@/api/order/basic';
import CustomDialog from '@/components/custom/dialog/index.vue';
import { useDictionaryStore } from '@/store';

// 字典仓库
const dictionaryStore = useDictionaryStore();
// props
const props = defineProps({
  // 订单id
  orderId: {
    type: Number,
    required: true,
  },
});
// emits
const emits = defineEmits(['requestSuccess']);
// 自定义对话框ref
const customDialogRef = useTemplateRef('customDialogRef');
// 处理打开对话框
const handleOpenDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
  customDialogRef.value.open(mode, params);
};
// 处理对话框设置数据
const handleDialogSetData = (params: Record<string, any>) => {
  const { list } = params;
  const includesKeys = list.map((item: Record<string, any>) => item.labelType);
  dictionaryStore.get('customer_label').forEach((item) => {
    if (!includesKeys.includes(item.value)) {
      list.push({
        orderId: props.orderId,
        labelType: item.value,
        content: '',
      });
    }
  });
  return {
    list,
  };
};
// 处理对话框保存数据
const handleDialogSaveData = (params: Record<string, any>) => {
  return params.list;
};
// 处理对话框请求成功
const handleDialogRequestSuccess = (result: Record<string, any>) => {
  emits('requestSuccess', result);
};
</script>
